import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, getInfo as getInfoApi, logout as logoutApi, getPlatformPermission } from '@/api/user'
import { clearToken, getToken, setToken, getPlaid, updateGlobalConfig } from '@/utils/auth'
import { resetRouter } from '@/router'
import { useMenuStore } from './menu'

export const useUserStore = defineStore('user', () => {
  // state
  const token = ref(getToken())
  const user = ref({})
  const roles = ref([])
  const permission = ref({})

  // actions
  // 登录
  const login = (loginData) => {
    return new Promise((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          if (response.code !== 0) {
            reject(new Error(response.message || '未知错误'))
          } else {
            token.value = response.data.token
            setToken(response.data.token)
            updateGlobalConfig()
            resolve(response.data)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取用户信息
  const getUserInfo = () => {
    return new Promise((resolve, reject) => {
      getInfoApi(token.value)
        .then(({ data }) => {
          if (!data) {
            reject(new Error('登录状态失效，请重新登录'))
            return
          }
          if (!data.roles || data.roles.length <= 0) {
            reject(new Error('getUserInfo：角色必须是非null数组！'))
            return
          }
          roles.value = data.roles
          user.value = data
          resolve(data)
        })
        .catch((error) => {
          console.log('error', error)
          reject(error)
        })
    })
  }

  // 获取用户权限
  const getUserPermission = () => {
    return new Promise((resolve, reject) => {
      getPlatformPermission(getPlaid())
        .then((response) => {
          const { data } = response
          permission.value[getPlaid()] = data
          resolve(data)
        })
        .catch((error) => {
          permission.value[getPlaid()] = ['not']
          reject(error)
        })
    })
  }

  // 退出登录
  const logout = () => {
    return new Promise((resolve, reject) => {
      logoutApi()
        .then(() => {
          const menuStore = useMenuStore()
          menuStore.clearMenu()
          token.value = ''
          user.value = {}
          roles.value = []
          permission.value = {}
          clearToken()
          resetRouter()
          location.reload() // 清空路由
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 重置Token
  const resetToken = () => {
    return new Promise((resolve) => {
      token.value = ''
      roles.value = []
      user.value = {}
      permission.value = {}
      clearToken()
      resetRouter()
      resolve()
    })
  }

  return {
    token,
    user,
    roles,
    permission,
    login,
    getUserInfo,
    getUserPermission,
    logout,
    resetToken
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore()
}
